package com.xyy.kingdeejdy.service.pop.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xyy.kingdeejdy.enums.JdMsgEnum;
import com.xyy.kingdeejdy.enums.TaskEnum;
import com.xyy.kingdeejdy.helper.JdHelper;
import com.xyy.kingdeejdy.param.JdCustomerFilter;
import com.xyy.kingdeejdy.param.JdProductFilter;
import com.xyy.kingdeejdy.param.JdStockFilter;
import com.xyy.kingdeejdy.pojo.erp.customer.Conta;
import com.xyy.kingdeejdy.pojo.erp.customer.CustomerRuInfo;
import com.xyy.kingdeejdy.pojo.erp.customer.JdCustomerInfo;
import com.xyy.kingdeejdy.pojo.erp.customer.JdCustomerPo;
import com.xyy.kingdeejdy.pojo.erp.help.JdyResult;
import com.xyy.kingdeejdy.pojo.erp.order.JdOrderDetail;
import com.xyy.kingdeejdy.pojo.erp.order.JdOrderSave;
import com.xyy.kingdeejdy.pojo.erp.order.OrderDetailSku;
import com.xyy.kingdeejdy.pojo.erp.order.OrderRuInfo;
import com.xyy.kingdeejdy.pojo.erp.product.JdProductInfoDto;
import com.xyy.kingdeejdy.pojo.erp.product.JdProductStockDto;
import com.xyy.kingdeejdy.pojo.erp.product.Stcok;
import com.xyy.kingdeejdy.pojo.erp.product.StockInfo;
import com.xyy.kingdeejdy.pojo.pop.*;
import com.xyy.kingdeejdy.service.erp.JdToPopService;
import com.xyy.kingdeejdy.service.pop.PopToErpService;
import com.xyy.kingdeejdy.utils.DateUtils;
import com.xyy.kingdeejdy.utils.IpUtils;
import com.xyy.kingdeejdy.utils.MD5Util;
import com.xyy.kingdeejdy.utils.http.RedirectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PopToErpServiceImpl implements PopToErpService {

    @Autowired
    private JdToPopService jdToPopService;
    private boolean isOutLog = false;
    private boolean isFull = false;

    //商品信息
    @Override
    public void ProductInfoPush(PopConfig popConfig) {

        int total = 500;
        int page = Page(total);
        //分批上报数据
        for (int i = 1; i <= page; i++) {
            List<PopErpSkuForInsertDto> popErpSkuForInsertDtoList = ProductInformationRep(i, total, popConfig);
            if (CollectionUtils.isEmpty(popErpSkuForInsertDtoList)) {
                continue;
            }
        }


    }

    //商品价格上报
    @Override
    public void ProductPricePush(PopConfig popConfig) {
        int total = 100;
        int page = Page(total);
        for (int i = 1; i <= page; i++) {
            List<PopErpSkuPriceDto> popErpSkuPriceDtoList = ProductPricermationRep(i, total, popConfig);
            if (popErpSkuPriceDtoList.isEmpty()) {
                continue;
            }
        }
    }

    //批次上报
    @Override
    public void ProductStockPush(PopConfig popConfig) {
        JdStockFilter jdStockFilter = new JdStockFilter();
        jdStockFilter.setPage(1);
        jdStockFilter.setPageSize(1);
        JdyResult jdyResult = jdToPopService.productStockBat(jdStockFilter);
        Integer records = jdyResult.getRecords();
        int pageSize = 500;
        int page = records % pageSize == 0 ? records / pageSize : records / pageSize + 1;
        for (int i = 1; i <= page; i++) {
            List<PopErpSkuStockV2Dto> popErpSkuStockV2Dtos = StockBatchP(i, pageSize, popConfig);
            if (CollectionUtils.isEmpty(popErpSkuStockV2Dtos)) {
                continue;
            }
        }
    }

    //客户信息上报
    @Override
    public void customerInfoPush(PopConfig popConfig) {
        JdCustomerFilter jdCustomerFilter = new JdCustomerFilter();
        jdCustomerFilter.setPage(1);
        jdCustomerFilter.setPageSize(1);
        jdCustomerFilter.setStatus(0);
        if (!isFull) {
            jdCustomerFilter.setUpdTimeBegin(DateUtils.getBeginDayOfMonth());
        }
        JdyResult jdyResult = jdToPopService.CustomerInfo(jdCustomerFilter);
        Integer records = jdyResult.getRecords();
        log.info("查询出客户总数: {}", records);
        int pageSize = 500;
        int page = records % pageSize == 0 ? records / pageSize : records / pageSize + 1;
        for (int i = 1; i <= page; i++) {
            List<PopErpClientInfoDto> infoDtoList = customerInfoBat(i, pageSize, popConfig);
            if (CollectionUtils.isEmpty(infoDtoList)) {
                continue;
            }
        }
    }

    //客户信息分批上报实现
    private List<PopErpClientInfoDto> customerInfoBat(int i, int pageSize, PopConfig popConfig) {
        JdCustomerFilter jdCustomerFilter = new JdCustomerFilter();
        jdCustomerFilter.setPage(i);
        jdCustomerFilter.setPageSize(pageSize);
        jdCustomerFilter.setStatus(0);
        if (!isFull) {
            jdCustomerFilter.setUpdTimeBegin(DateUtils.getBeginDayOfMonth());
        }
        JdyResult jdyResult = jdToPopService.CustomerInfo(jdCustomerFilter);
        List<JdCustomerInfo> jdCustomerInfos = JSON.parseArray(JSON.toJSONString(jdyResult.getItems()), JdCustomerInfo.class);
        List<PopErpClientInfoDto> infoDtoList = JdHelper.convertToPopErpClientInfoDtos(popConfig.getOrgId(), jdCustomerInfos);
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.CLIENT_INFO.getTaskId(), infoDtoList, popConfig);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#客户信息上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        if (isOutLog) {
            log.info("客户信息上报成功,JsonData: {}", JSON.toJSONString(infoDtoList.stream().map(m -> m.getCustomerName()).collect(Collectors.toList())));
        }
        return infoDtoList;
    }

    //库存分批上报实现
    private List<PopErpSkuStockV2Dto> StockBatchP(int i, int pageSize, PopConfig popConfig) {
        JdStockFilter jdStockFilter = new JdStockFilter();
        jdStockFilter.setPage(i);
        jdStockFilter.setPageSize(pageSize);
        JdyResult jdyResult = jdToPopService.productStockBat(jdStockFilter);
        String jsonString = JSON.toJSONString(jdyResult.getItems());
        List<JdProductStockDto> jdProductStockDtos = JSON.parseArray(jsonString, JdProductStockDto.class);
        //没效期不同步库存
        Map<String, List<JdProductStockDto>> collect = jdProductStockDtos.stream().filter(m -> m.getValidDate() != null && m.getProdDate() != null).collect(Collectors.groupingBy(JdProductStockDto::getProductNumber));
        //转换成POP库存对象
        List<PopErpSkuStockV2Dto> popErpSkuStockV2Dtos = JdHelper.convertToPopErpSkuStockDtos(collect);
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.PRODUCT_STOCK.getTaskId(), popErpSkuStockV2Dtos, popConfig);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#库存信息上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        if (isOutLog) {
            log.info("库存信息上报成功,JsonData: {}", JSON.toJSONString(objectMap));
        }
        return popErpSkuStockV2Dtos;
    }


    //商品价格分批上报实现
    private List<PopErpSkuPriceDto> ProductPricermationRep(int pageNum, int total, PopConfig popConfig) {
        JdProductFilter filter = new JdProductFilter();
        filter.setPage(pageNum);
        filter.setPageSize(total);
        filter.setStatus("0");
        filter.setCategoryId("12961928509993152");
        JdyResult jdyResult = jdToPopService.productInfoList(filter);
        if (jdyResult == null || jdyResult.getItems() == null) {
            return new ArrayList<>();
        }
        List<JdProductInfoDto> jdProductInfoDtos = JSON.parseArray(JSON.toJSONString(jdyResult.getItems()), JdProductInfoDto.class);
        if (jdProductInfoDtos.size() <= 0 || jdProductInfoDtos.isEmpty()) {
            log.warn("金蝶返回商品数据: {},查询条件: {}", JSON.toJSONString(jdyResult), JSON.toJSONString(filter));
            return new ArrayList<>();
        }
        List<PopErpSkuPriceDto> popErpSkuPriceDtoList = new ArrayList<>();
        for (JdProductInfoDto jdProductInfoDto : jdProductInfoDtos) {
            PopErpSkuPriceDto erpSkuPriceDto = new PopErpSkuPriceDto();
            BigDecimal wholeSalePrice = jdProductInfoDto.getWholeSalePrice();
            BigDecimal price = BigDecimal.valueOf(9999);
            if (wholeSalePrice.compareTo(BigDecimal.ZERO) <= 0) {
                wholeSalePrice = price;
            }
            erpSkuPriceDto.setErpCode(jdProductInfoDto.getProductNumber());
            erpSkuPriceDto.setMonomerPrice(wholeSalePrice);
            erpSkuPriceDto.setChainPrice(wholeSalePrice);
            erpSkuPriceDto.setBasePrice(wholeSalePrice);
            popErpSkuPriceDtoList.add(erpSkuPriceDto);
        }
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.PRODUCT_PRICE.getTaskId(), popErpSkuPriceDtoList, popConfig);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#商品价格上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        if (isOutLog) {
            log.info("商品价格上报成功,JsonData: {}", JSON.toJSONString(popErpSkuPriceDtoList));
        }
        return popErpSkuPriceDtoList;
    }

    //数据筛选接口
    @Override
    public List<String> queryData(Integer taskId, PopConfig popConfig) {
        //查询出需要上传库存的品
        Map<String, Object> objectMap = buildPopTaskQueryParam(taskId, null, popConfig);
        String body = RedirectUtil.doGetParam("https://h-api.ybm100.com/api/hackTask/queryTaskCondition", objectMap);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult.getData() == null) {
            log.warn("#平台暂时无可用数据 apiRPCResult：{}", JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        QueryTaskData queryTaskData = JSON.parseObject(dataJson, QueryTaskData.class);
        return queryTaskData.getListQueryParam();
    }

    @Override
    public void orderInfoPull(PopConfig popConfig) {
        List<SellerOrderInfoDto> sellerOrderInfoDtos = pullDataInfo(TaskEnum.ORDER_TOTAL.getTaskId(), SellerOrderInfoDto.class, popConfig);
        if (sellerOrderInfoDtos.isEmpty()) {
            return;
        }
        convertOrderInfo(sellerOrderInfoDtos, popConfig);
    }

    @Override
    public void customerInfoPull(PopConfig popConfig) {
        List<PlatformCustomerDto> platformCustomerDtos = pullDataInfo(TaskEnum.CLIENT_PUSH_DOWN.getTaskId(), PlatformCustomerDto.class, popConfig);
        if (platformCustomerDtos.isEmpty()) {
            return;
        }
        //转金蝶客户
        convertCustomerInfo(platformCustomerDtos, popConfig);
    }

    @Override
    public void orderDeliver(PopConfig popConfig) {
        //查询出需要回传明细得订单号
        List<String> list = queryData(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId(), popConfig);
        if (list.size() <= 0 && list.isEmpty()) {
            log.info("目前暂无需要同步待配送订单!!!!");
            return;
        }
        List<SellerOrderDeliverDetailDto> orderDeliverDetailDtos = jdToPopService.jdOrderInfoToNumber(list);
        if (orderDeliverDetailDtos.isEmpty()) {
            return;
        }
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId(), orderDeliverDetailDtos, popConfig);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#出库明细任务上报失败  apiRPCResult: {},Data: {}", JSON.toJSONString(body), JSON.toJSONString(orderDeliverDetailDtos));
            return;
        }
        log.info("#出库明细 上报成功订单 Data: {}", JSON.toJSONString(orderDeliverDetailDtos));
    }

    @Override
    public void realStockPush(PopConfig popConfig) {
        Stcok stcok = new Stcok();
        stcok.setPage(1);
        stcok.setPageSize(1);
        JdyResult jdyResult = jdToPopService.RealStock(stcok);
        Integer records = jdyResult.getRecords();
        int pageSize = 500;
        int page = records % pageSize == 0 ? records / pageSize : records / pageSize + 1;
        for (int i = 1; i <= page; i++) {
            List<PopErpSkuStockV2Dto> popErpSkuStockV2Dtos = realStockBat(i, pageSize, popConfig);
            if (CollectionUtils.isEmpty(popErpSkuStockV2Dtos)) {
                continue;
            }
        }

    }

    private List<PopErpSkuStockV2Dto> realStockBat(int i, int pageSize, PopConfig popConfig) {
        Stcok stcok = new Stcok();
        stcok.setPage(i);
        stcok.setPageSize(pageSize);
        JdyResult jdyResult = jdToPopService.RealStock(stcok);
        if (jdyResult == null || jdyResult.getItems() == null) {
            return new ArrayList<>();
        }
        String jsonString = JSON.toJSONString(jdyResult.getItems());
        List<StockInfo> stockInfoList = JSON.parseArray(jsonString, StockInfo.class);
        //转换成POP库存对象
        List<PopErpSkuStockV2Dto> popErpSkuStockV2Dtos = new ArrayList<>();
        //处理pop对象
        for (StockInfo stockInfo : stockInfoList) {
            PopErpSkuStockV2Dto erpSkuStockV2Dto = new PopErpSkuStockV2Dto();
            erpSkuStockV2Dto.setErpCode(stockInfo.getProductNumber());
            erpSkuStockV2Dto.setAvailableQyt(stockInfo.getQty() <= 0 ? 0 : stockInfo.getQty());
            popErpSkuStockV2Dtos.add(erpSkuStockV2Dto);
        }
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.PRODUCT_STOCK.getTaskId(), popErpSkuStockV2Dtos, popConfig);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#库存信息上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        if (isOutLog) {
            log.info("库存信息上报成功,JsonData: {}", JSON.toJSONString(objectMap));
        }
        return popErpSkuStockV2Dtos;


    }

    //转金蝶客户
    private void convertCustomerInfo(List<PlatformCustomerDto> platformCustomerDtos, PopConfig popConfig) {
        for (PlatformCustomerDto popInfo : platformCustomerDtos) {
            JdCustomerPo customerPo = new JdCustomerPo();
            customerPo.setNumber("YBM" + popInfo.getMerchantId());
            customerPo.setName(popInfo.getCustomerName());
            customerPo.setLevel("1");
            customerPo.setTaxPayerNo(popInfo.getTaxpayerIdentity());
            customerPo.setBank(popInfo.getRegisteredBank());
            customerPo.setCardNo(popInfo.getRegisteredBankAccount().replace(" ", ""));
            customerPo.setRemark("药帮忙客户");
            Conta conta = new Conta();
            conta.setName(popInfo.getPickName());
            conta.setMobile(popInfo.getPickPhone());
            conta.setPrimary(true);
            conta.setAddress(popInfo.getPickAddress());
            customerPo.setContacts(Collections.singletonList(conta));
            customerPo.setDeleted(false);
            JdyResult jdCustomer = jdToPopService.toJdCustomer(Collections.singletonList(customerPo));
            List<CustomerRuInfo> customerRuInfos = JSON.parseArray(JSON.toJSONString(jdCustomer.getItems()), CustomerRuInfo.class);
            CustomerRuInfo customerRuInfo = customerRuInfos.get(0);
            if (JdMsgEnum.CUSTOMER_DUP.getMsg().equals(customerRuInfo.getMsg()) || JdMsgEnum.SUCCESS.getMsg().equals(customerRuInfo.getMsg())) {
                log.info("客户信息导入金蝶成功 Data: {}", popInfo.getCustomerName());
                extracted(popInfo, popConfig);
            }
        }


    }

    //转金蝶订单
    private void convertOrderInfo(List<SellerOrderInfoDto> sellerOrderInfoDtos, PopConfig popConfig) {
        List<JdOrderSave> orderSaveList = new ArrayList<>();
        for (SellerOrderInfoDto popOrder : sellerOrderInfoDtos) {
            JdOrderSave jdOrderSave = new JdOrderSave();
            jdOrderSave.setNumber(popOrder.getOrderNo());
            jdOrderSave.setDate(popOrder.getOrderCreateTime());
            jdOrderSave.setCustomerNumber(popOrder.getVenderCode());
            jdOrderSave.setDiscRate(0);
            jdOrderSave.setContactAddr(popOrder.getPickAddress());
            List<SellerOrderDetailDto> sellerOrderDetailLists = popOrder.getSellerOrderDetailLists();
            List<JdOrderDetail> orderDetails = new ArrayList<>();
            for (SellerOrderDetailDto sellerOrderDetailList : sellerOrderDetailLists) {
                OrderDetailSku orderDetailSku = jdToPopService.productInfoSku(sellerOrderDetailList.getErpCode());
                if (orderDetailSku == null || orderDetailSku.getUnitId() == null || BeanUtil.isEmpty(orderDetailSku)) {
                    log.warn("金蝶未查询到商品信息,erp_code: {}", sellerOrderDetailList.getErpCode());
                    continue;
                }
                // TODO: 2023/7/29 可能需要分摊批号
                JdOrderDetail jdOrderDetail = new JdOrderDetail();
                jdOrderDetail.setUnit(orderDetailSku.getUnitId());
                //商品编码
                jdOrderDetail.setProductNumber(sellerOrderDetailList.getErpCode());
                //批号
                jdOrderDetail.setBatch(orderDetailSku.getBatch());
                //仓库编码
                jdOrderDetail.setLocation("CK001");
                //单价
                jdOrderDetail.setPrice(sellerOrderDetailList.getSkuPurchasePrice());
                //下单数量
                jdOrderDetail.setQty(sellerOrderDetailList.getPurchaseNum());
                //生产日期
                jdOrderDetail.setProdDate(orderDetailSku.getProdDate());
                //明细备注 用来放订单明细ID
                jdOrderDetail.setRemark(String.valueOf(sellerOrderDetailList.getOrderDetailId()));
                orderDetails.add(jdOrderDetail);
            }
            if (orderDetails.isEmpty()) {
                log.info("当前订单商品导入金蝶异常请核对商品编码,order_no: {}", popOrder.getOrderNo());
                continue;
            }
            //添加金蝶明细
            jdOrderSave.setEntries(orderDetails);
            orderSaveList.add(jdOrderSave);
        }
        if (orderSaveList.isEmpty()) {
            log.warn("订单导入金蝶明细异常");
            return;
        }
        JdyResult jdOrderInfo = jdToPopService.toJdOrderInfo(orderSaveList);
        List<OrderRuInfo> orderRuInfos = JSON.parseArray(JSON.toJSONString(jdOrderInfo.getItems()), OrderRuInfo.class);
        OrderRuInfo orderRuInfo = orderRuInfos.get(0);
        if (JdMsgEnum.SUCCESS.getMsg().equals(orderRuInfo.getMsg()) || JdMsgEnum.ORDER_DUP.getMsg().equals(orderRuInfo.getMsg()) || JdMsgEnum.ORDER_PART.getMsg().equals(orderRuInfo.getMsg())) {
            log.info("订单导入金蝶成功: {}", JSON.toJSONString(orderRuInfo.getEntries()));
        }
        List<String> collect = orderRuInfos.stream().map(m -> m.getNumber()).collect(Collectors.toList());
        extracted(collect, popConfig);
    }

    //商品分批上报实现
    private List<PopErpSkuForInsertDto> ProductInformationRep(int pageNum, int pageSize, PopConfig popConfig) {
        JdProductFilter filter = new JdProductFilter();
        filter.setPage(pageNum);
        filter.setPageSize(pageSize);
        filter.setStatus("0");
        //商品类别
        filter.setCategoryId("12961928509993152");
        JdyResult jdyResult = jdToPopService.productInfoList(filter);
        if (jdyResult.getCode() != 0) {
            log.info("筋斗云未查询到商品信息: {}", JSON.toJSONString(jdyResult));
        }
        List<JdProductInfoDto> jdProductInfoDtos = JSON.parseArray(JSON.toJSONString(jdyResult.getItems()), JdProductInfoDto.class);
        if (jdProductInfoDtos.size() <= 0 || jdProductInfoDtos.isEmpty()) {
            log.info("金蝶返回商品数据: {},查询条件: {}", JSON.toJSONString(jdyResult), JSON.toJSONString(filter));
            return new ArrayList<>();
        }
        List<PopErpSkuForInsertDto> popErpSkuForInsertDtoList = new ArrayList<>();
        for (JdProductInfoDto jdProduct : jdProductInfoDtos) {
            PopErpSkuForInsertDto popProduct = new PopErpSkuForInsertDto();
            popProduct.setErpCode(jdProduct.getProductNumber());
            popProduct.setProductName(jdProduct.getProductName());
            popProduct.setCommonName(jdProduct.getProductName());
            popProduct.setApprovalNumber("");
            popProduct.setCode(jdProduct.getBarcode());
            popProduct.setManufacturer(jdProduct.getRemark());
            popProduct.setMediumPackageNum(1);
            popProduct.setSpec(jdProduct.getSpec());
            popProduct.setDosageForm("无");
            popProduct.setTerm("36");
            popProduct.setSuggestPrice(jdProduct.getWholeSalePrice());
            popProduct.setProductUnit(jdProduct.getUnitName());
            popProduct.setAvailableQyt(jdProduct.getLowQty());
            popErpSkuForInsertDtoList.add(popProduct);
        }
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.PRODUCT_FULL.getTaskId(), popErpSkuForInsertDtoList, popConfig);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#商品信息上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        if (isOutLog) {
            log.info("商品信息上报成功,JsonData: {}", JSON.toJSONString(jdProductInfoDtos.stream().map(m -> m.getProductNumber()).collect(Collectors.toList())));
        }
        return popErpSkuForInsertDtoList;
    }


    //构建参数方法
    private <T> Map<String, Object> buildPopTaskQueryParam(Integer taskId, List<T> list, PopConfig popConfig) {


        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(popConfig.getOrgId());
        taskQueryParam.setAppId(popConfig.getAppId());
        if (taskId != null && taskId != 00000) {
            taskQueryParam.setTaskId(taskId);
        }
        if (taskId == 00000) {
            String ipAddress = "";
            InetAddress address = IpUtils.getLocalHostLANAddress();
            if (address != null) {
                ipAddress = address.getHostAddress();
            }
            taskQueryParam.setVersion("3.5");
            taskQueryParam.setJsonData(ipAddress);
        }
        if (!CollectionUtils.isEmpty(list)) {
            taskQueryParam.setJsonData(JSON.toJSONString(list));
        }
        Map<String, Object> popParamMap = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        //log.info("加密参数{}", JSON.toJSONString(popParamMap));
        taskQueryParam.setSign(MD5Util.encrypt(popParamMap, popConfig.getAppSecret()));
        Map<String, Object> popParamMapNew = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        return popParamMapNew;
    }

    //获取商品分页数据
    private int Page(int pageSize) {
        JdProductFilter filter = new JdProductFilter();
        filter.setStatus("0");
        filter.setPage(1);
        filter.setPageSize(1);
        filter.setCategoryId("12961928509993152");
        JdyResult jdyResult = jdToPopService.productInfoList(filter);
        int records = jdyResult.getRecords();
        int totalPage = records % pageSize == 0 ? records / pageSize : records / pageSize + 1;
        return totalPage;
    }

    public <T> List<T> pullDataInfo(Integer taskId, Class<T> tClass, PopConfig popConfig) {
        //构建pop订单查询参数
        //构建查询pop参数
        Map<String, Object> objectMap = buildPopTaskQueryParam(taskId, null, popConfig);
        String body = RedirectUtil.doGetParam("https://h-api.ybm100.com/api/hackTask/pullDataInfo", objectMap);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#平台数据下推失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        if (apiRPCResult.getData() == null) {
            log.warn("#平台暂无可拉取数据 apiRPCResult：{}", JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        log.info("#拉取到的通知信息: DataInfo: {}", dataJson);
        List<T> ts = JSON.parseArray(dataJson, tClass);
        return ts;
    }

    //订单回调
    public void extracted(List<String> sellerOrderInfoDtos, PopConfig popConfig) {
        List<SellerOrderCallBackDto> orderCallBackDtos = new ArrayList<>();
        for (String sellerOrderInfoDto : sellerOrderInfoDtos) {
            SellerOrderCallBackDto sellerOrderCallBackDto = new SellerOrderCallBackDto();
            sellerOrderCallBackDto.setOrderNo(sellerOrderInfoDto);
            sellerOrderCallBackDto.setType(1);
            sellerOrderCallBackDto.setOrgId(popConfig.getOrgId());
            sellerOrderCallBackDto.setResult(true);
            orderCallBackDtos.add(sellerOrderCallBackDto);
        }
        //订单信息回调
        Map<String, Object> callTask = buildPopTaskQueryParam(10086, orderCallBackDtos, popConfig);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/callbackForPullTask", JSON.toJSONString(callTask));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.info("###订单回调失败, orderNo: {}", JSON.toJSONString(orderCallBackDtos));
        }
        log.info("###订单回调成功, orderNo: {}", JSON.toJSONString(orderCallBackDtos));
    }

    //客户回调
    public void extracted(PlatformCustomerDto row, PopConfig popConfig) {
        List<SellerCustomerCallBackDto> callBackDtos = new ArrayList<>();
        SellerCustomerCallBackDto customerCallBackDto = new SellerCustomerCallBackDto();
        customerCallBackDto.setId(row.getId());
        customerCallBackDto.setNo(row.getCustomerName());
        customerCallBackDto.setResult(true);
        customerCallBackDto.setOrgId(popConfig.getOrgId());
        callBackDtos.add(customerCallBackDto);
        //客户信息回调
        Map<String, Object> callTask = buildPopTaskQueryParam(10086, callBackDtos, popConfig);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/callbackForCustomerPullTask", JSON.toJSONString(callTask));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.info("###客户回调失败, orderNo: {}", JSON.toJSONString(callBackDtos));
        }
        log.info("###客户回调成功, orderNo: {}", JSON.toJSONString(callBackDtos));
    }
}
